/*
 * @lc app=leetcode.cn id=54 lang=javascript
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  let len = matrix.length;
  if (len == 0) {
    return matrix;
  }
  let size=len*matrix[0].length
  let res = [];
  let lines = matrix.length - 1;
  let columns = matrix[0].length - 1;
  let dfs = function (i, j, lines, columns) {
    if (i > lines || j > columns) return;
    if(matrix[i]){
        res.push(...matrix[i].slice(j,columns+1))
        if(size===res.length)return
    }
    for (let line = i + 1; line < lines; line++) {
      if (matrix[line]) res.push(matrix[line][columns]);
    }
    res.push(...matrix[lines].slice(j,columns+1).reverse());
    if(size===res.length)return
    for (let line = lines - 1; line > i; line--) {
      res.push(matrix[line][j]);
    }
    dfs(i + 1, j + 1, lines - 1, columns - 1);
  };
  dfs(0, 0, lines, columns);
  return res
};
// @lc code=end

console.log(
  spiralOrder([
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16],
  ])
);

// const visited = new Array(rows).fill(0).map(() => new Array(columns).fill(false));
//节点标记这一行很好用